<template lang="pug">
  el-row
    el-col(:span="24" v-loading="loading")
      .header-box
        .headImgBox
          el-avatar(:size="100" :src="info.headUrl || defaultImg")
        .info
          h2
            | {{info.name}}
            el-tag.ml5(v-if="info.status" size="medium" effect="dark") {{info.statusVal}}
          p
            span
              i.mr5(class="iconfont icon-zerenren c_secondary")
              | 负责人：
              b {{info.staffName}}
        .btnGroups
          el-button.gradientVertical(v-if="info.status === 1" size="large" round @click="() => modalHandle('stop')") 终止合同
          el-button(v-if="info.status === 1" size="large" round @click="freezeHandle") 冻结合同
          el-button(v-if="info.status === 5" size="large" round @click="unfreezeHandle") 解冻合同
          el-button(size="large" round @click="() => modalHandle('contractTransfer')") 移交
          el-button(v-if="info.status === 4" size="large" round @click="() => modalHandle('backMoney')") 添加回款记录
    el-col(:span="24")
      el-divider
      el-row(:gutter="24")
        el-col(:span="14")
          .drawer-content(v-loading="loading")
            form-info(:items="infoItems")
          s-table(
            ref="productTable"
            :dataPops="info.contractProducts || []"
            :column="productColum"
          )
            template(slot="practicalTotalAmount" slot-scope="text, scope")
              p ￥{{text | toThousandFilter}}
              small.c_warning 折扣：{{scope.practicalAmount | toPercent(scope.standardUnitAmount)}}
          alert(type="info")
            p
              | 标准价格合计:
              span(v-for="(item, index) in (info.contractProducts || [])" :key="item.id")
                small ￥
                | {{item.standardUnitAmount | toThousandFilter}} * {{item.count}}
                span.ml5.mr5(v-if="index !== (info.contractProducts || []).length - 1") +
              span.ml5.mr5 =
              | {{standardUnitAmount | toThousandFilter}}
            p
              | 实际销售合计:
              span(v-for="(item, index) in (info.contractProducts || [])" :key="item.id")
                small ￥
                | {{item.practicalAmount | toThousandFilter}} * {{item.count}}
                span.ml5.mr5(v-if="index !== (info.contractProducts || []).length - 1") +
              span.ml5.mr5 =
              | {{practicalAmount | toThousandFilter}}
            p
              | 合同金额合计:
              span.f18.c_error
                small ￥
                | {{practicalAmount | toThousandFilter}}
              el-tag.ml5.vm(type="warning" size="mini") 折扣: {{practicalAmount | toPercent(standardUnitAmount)}}
          form-info.mt16(:items="infoOtherItems")
        el-col(:span="10")
          follow-list(:id="id" paramsKey="contractId" type="leadsHistoryByContract" ref="followList")
      modal-form(
        title="终止合同"
        width="560px"
        :visible.sync="modalObj.stopVisible"
        :fields="stopItems"
        :submitting="stopSubmitting"
        :submitHandle="stopSubmitHandle"
        :layoutCol="{xs: 24, md: 24, lg: 24}"
      )
      back-money(:visible.sync="modalObj.backMoneyVisible" :id="id" :info="info" @getInfo="getInfo")
      contract-transfer(:visible.sync="modalObj.contractTransferVisible" :id="id" :info="info" @getInfo="getInfo")
</template>
<script>

import { mapGetters } from 'vuex'
import defaultImg from '@/assets/TX2.png'
import dictMixin from '@/mixins/dict'
import Alert from '@/components/Basic/Alert'
import FormInfo from '@/components/Basic/Form/FormInfo'
import { getContractInfo, contractFreeze, contractUnfreeze, contractStop } from '../../api'
import { infoItems, infoOtherItems, productColum, stopItems } from './config'
import Attachment from '../../components/attachment'
import ContractTransfer from '../../components/clueTransfer'
import BackMoney from '../../components/contractBackMoney'
import FollowList from '../../components/followList'

export default {
  components: {
    FormInfo,
    Alert,
    Attachment,
    contractTransfer: ContractTransfer,
    backMoney: BackMoney,
    FollowList
  },
  mixins: [dictMixin],
  data () {
    return {
      defaultImg,
      productColum,
      stopItems: stopItems(),
      loading: false,
      submitting: false,
      activeTab: 'detail',
      info: {},
      disabled: true,
      history: [],
      modalObj: {
        contractTransferVisible: false,
        backMoneyVisible: false,
        stopVisible: false
      },
      stopSubmitting: false
    }
  },
  computed: {
    ...mapGetters(['curArea', 'dict', 'user']),
    infoItems () {
      return infoItems(this.info)
    },
    infoOtherItems () {
      return infoOtherItems(this.info)
    },
    id () {
      return this.$route.query.id
    },
    // 计算意向产品总金额
    standardUnitAmount () {
      const productRecords = this.info.contractProducts || []
      return productRecords.reduce((sum, cur) => {
        return sum + (cur.standardUnitAmount || 0) * (cur.count || 1)
      }, 0)
    },
    // 计算意向产品折扣后总金额
    practicalAmount () {
      const productRecords = this.info.contractProducts || []
      return productRecords.reduce((sum, cur) => {
        return sum + (cur.practicalAmount || 0) * (cur.count || 1)
      }, 0)
    }
  },
  created () {
    this.getInfo()
  },
  methods: {
    // 获取详情
    getInfo () {
      const { id } = this
      if (id) {
        this.loading = true
        getContractInfo({ contractId: id }).then(res => {
          this.info = res || {}
        }).finally(() => {
          this.loading = false
        })
        this.$refs.followList && this.$refs.followList.getLeadsHistory()
      }
    },
    // 移交
    modalHandle (type) {
      this.modalObj = {
        [`${type}Visible`]: true
      }
    },
    // 冻结
    freezeHandle () {
      const { id, info } = this
      this.$prompt('所有该宝宝的关联合同都将改为冻结状态，需解冻后才能上课', '冻结原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea'
      }).then(({ value }) => {
        contractFreeze({ contractId: id, clienteleId: info.clienteleId, content: value }).then(() => {
          this.$message.success('冻结合同成功')
          this.getInfo()
        })
      })
    },
    // 解冻
    unfreezeHandle () {
      const { id, info } = this
      this.$confirm('此操作会解冻该宝宝的所有关联合同，是否解冻恢复上课??', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        contractUnfreeze({ contractId: id, clienteleId: info.clienteleId }).then(() => {
          this.$message.success('删除成功')
          this.getInfo()
        })
      })
    },
    // 终止
    stopSubmitHandle (values) {
      console.log(values)
      const { id, user } = this
      this.stopSubmitting = true
      contractStop({ contractId: id, staffId: user.id, ...values }).then(() => {
        this.$message.success('提交成功')
        this.getInfo()
      }).finally(() => {
        this.stopSubmitting = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.header-box{
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;

  .headImgBox{
    width: 100px;
    height: 100px;
    margin-right: 20px;
    border-radius: 50%;
    background: #fff;
    border: 2px solid #FFFFFF;
    box-shadow: 0px 6px 18px 0px rgba(0, 0, 0, 0.2);
    border-radius: 50%;
  }

  .info {
    h2 {
      font-size: 22px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #333333;
      margin: 0 20px 15px 0;

      ::v-deep{
        .el-tag {
          font-weight: normal;
          font-size: 15px;
          height: 25px;
          line-height: 25px;
          border: none;
          background: #2DB7F5;
          border-radius: 3px;
        }
      }
    }

    > p {
      font-size: 15px;
      font-family: PingFang SC;
      ;
      color: #666666;

      b {
        margin-left: 5px;
      }
    }
  }

  .btnGroups{
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
  }
}

::v-deep {
  .tableWrapper{
    padding-left: 0;
    padding-right: 0
  }
}

</style>
